﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Web;
using System.Web.Mvc;
using CarBooker.Models;

namespace CarBooker.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        static private ICarService bookableCars = new CarService();

        public HomeController() {
            bookableCars = bookableCars ?? new CarService();
        }
        public HomeController(CarService carService)
        { 
            bookableCars = carService;
        }
  
        public ActionResult Index()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult AskCars()
        {
            return View();
        }

        public ActionResult AddCars()
        {
            return View(); //ToDo: reload the data
        }

        [HttpPost]
        [ActionName("AddCars")]
        public ActionResult AddCars(CarDescription description)
        {
            AddCar(description);
            ViewData["Message"] = "Car added: " + description;
            return View();
        }
        
        public ActionResult GetCars() //comes here if AvailableCars in url
        {
           // return AvailableCars(new BookingRequest()); //ToDo: reload the data
            return View(ListNotNull(null));
        }

        [HttpPost]
        [ActionName("GetCars")]
        public ActionResult GetCars(BookingRequest enquiry)
        {
            ViewData["Message"] = "Cars found:";
            return View(FindCars(enquiry));           
         }
        private static List<Models.Car> FindCars(BookingRequest carEnquiry)
        { 
            return ListNotNull(bookableCars.AvailableCars(carEnquiry));
        }

        private static List<CarBooker.Models.Car> ListNotNull(List<CarBooker.Models.Car> result)
        {
            if (result == null) 
            { result = new List<Models.Car>(); }
            return result;
        }

        private static void AddCar(CarDescription description)
        {
            bookableCars.AddCar(description);
        }
    }
}
